const Service = require('egg').Service;

class CirclePostCommentService extends Service {
    // 创建评论
    async create(commentData) {
        const { ctx } = this;

        // 检查帖子是否存在
        const post = await ctx.model.CirclePost.findByPk(commentData.circle_post_id);
        if (!post) {
            throw new Error('帖子不存在');
        }

        // 如果parent_id存在，检查父评论是否存在且属于同一个帖子
        if (commentData.parent_id) {
            const parentComment = await ctx.model.CirclePostComment.findByPk(commentData.parent_id);
            if (!parentComment) {
                throw new Error('父评论不存在');
            }

            if (parentComment.circle_post_id != commentData.circle_post_id) {
                throw new Error('父评论不属于该帖子');
            }
        }

        // 创建评论
        const comment = await ctx.model.CirclePostComment.create({
            ...commentData,
            created_at: new Date(),
            updated_at: new Date(),
        });

        // 更新帖子的评论计数
        await post.increment('comment_count');

        // 获取完整的评论信息（包含用户信息）
        const result = await this.getCommentWithUser(comment.comment_id);

        return result;
    }

    // 检查用户是否加入了该圈子
    async checkUserInCircle(user_id, circle_post_id) {
        const { ctx } = this;

        // 获取帖子对应的圈子ID
        const post = await ctx.model.CirclePost.findByPk(circle_post_id, {
            attributes: ['circle_id']
        });

        if (!post) {
            throw new Error('帖子不存在');
        }

        // 检查用户是否加入了该圈子
        const userCircle = await ctx.model.UserCircle.findOne({
            where: {
                user_id,
                circle_id: post.circle_id
            }
        });

        if (!userCircle) {
            throw new Error('请先加入该圈子才能评论');
        }

        return true;
    }

    // 获取评论列表（分页）
    async getComments(circle_post_id, query = {}) {
        const { ctx } = this;
        const { page = 1, pageSize = 20 } = query;

        const options = {
            where: {
                circle_post_id,
                parent_id: null // 只获取顶级评论
            },
            include: [
                {
                    model: ctx.model.User,
                    as: 'commenter',
                    attributes: ['user_id', 'nickname', 'avatar']
                }
            ],
            limit: parseInt(pageSize),
            offset: (parseInt(page) - 1) * parseInt(pageSize),
            order: [['created_at', 'DESC']]
        };

        const { count, rows } = await ctx.model.CirclePostComment.findAndCountAll(options);

        // 获取每个评论的回复数量
        const commentsWithReplyCount = await Promise.all(
            rows.map(async (comment) => {
                const replyCount = await ctx.model.CirclePostComment.count({
                    where: { parent_id: comment.comment_id }
                });
                return {
                    ...comment.toJSON(),
                    reply_count: replyCount
                };
            })
        );

        return {
            list: commentsWithReplyCount,
            pagination: {
                page: parseInt(page),
                pageSize: parseInt(pageSize),
                total: count,
                totalPages: Math.ceil(count / pageSize)
            }
        };
    }

    // 根据ID获取评论详情
    async getCommentById(commentId) {
        const { ctx } = this;

        const comment = await ctx.model.CirclePostComment.findByPk(commentId, {
            include: [
                {
                    model: ctx.model.User,
                    as: 'commenter',
                    attributes: ['user_id', 'nickname', 'avatar']
                },
                {
                    model: ctx.model.CirclePost,
                    as: 'circlePost',
                    attributes: ['post_id', 'circle_id', 'content']
                }
            ]
        });

        if (!comment) {
            throw new Error('评论不存在');
        }

        return comment;
    }

    // 获取评论详情（包含用户信息）
    async getCommentWithUser(commentId) {
        const { ctx } = this;

        const comment = await ctx.model.CirclePostComment.findByPk(commentId, {
            include: [
                {
                    model: ctx.model.User,
                    as: 'commenter',
                    attributes: ['user_id', 'nickname', 'avatar']
                }
            ]
        });

        if (!comment) {
            throw new Error('评论不存在');
        }

        return comment;
    }

    // 更新评论
    async updateComment(commentId, updateData, userId) {
        const { ctx } = this;

        // 检查评论是否存在
        const comment = await ctx.model.CirclePostComment.findByPk(commentId);
        if (!comment) {
            throw new Error('评论不存在');
        }

        // 检查评论是否属于当前用户
        if (comment.user_id !== userId) {
            throw new Error('无权修改此评论');
        }

        // 更新评论信息
        await comment.update({
            ...updateData,
            updated_at: new Date()
        });

        // 返回更新后的评论信息
        const updatedComment = await this.getCommentWithUser(commentId);
        return updatedComment;
    }

    // 删除评论
    async deleteComment(commentId, userId) {
        const { ctx } = this;

        const comment = await ctx.model.CirclePostComment.findByPk(commentId);
        if (!comment) {
            throw new Error('评论不存在');
        }

        // 检查评论是否属于当前用户
        if (comment.user_id !== userId) {
            throw new Error('无权删除此评论');
        }

        // 检查是否有回复，如果有回复则不允许删除
        const replyCount = await ctx.model.CirclePostComment.count({
            where: { parent_id: commentId }
        });

        if (replyCount > 0) {
            throw new Error('该评论有回复，无法删除');
        }

        // 更新帖子的评论计数
        const post = await ctx.model.CirclePost.findByPk(comment.circle_post_id);
        if (post && post.comment_count > 0) {
            await post.decrement('comment_count');
        }

        await comment.destroy();
        return true;
    }

    // 获取评论的回复列表
    async getReplies(commentId, query = {}) {
        const { ctx } = this;
        const { page = 1, pageSize = 20 } = query;

        const options = {
            where: {
                parent_id: commentId
            },
            include: [
                {
                    model: ctx.model.User,
                    as: 'commenter',
                    attributes: ['user_id', 'nickname', 'avatar']
                }
            ],
            limit: parseInt(pageSize),
            offset: (parseInt(page) - 1) * parseInt(pageSize),
            order: [['created_at', 'ASC']] // 回复按时间正序排列
        };

        const { count, rows } = await ctx.model.CirclePostComment.findAndCountAll(options);

        return {
            list: rows,
            pagination: {
                page: parseInt(page),
                pageSize: parseInt(pageSize),
                total: count,
                totalPages: Math.ceil(count / pageSize)
            }
        };
    }
}

module.exports = CirclePostCommentService;